TOP_PATH := $(shell pwd)
exist_tsfile = $(shell if [ -f $(TOP_PATH)/tsfile.mk ]; then echo "exist"; else echo "notsfile"; fi;)
ifdef tsfile
TARGETS_FILE := $(tsfile)
else
ifeq ($(exist_tsfile), exist)
include tsfile.mk
else
TARGETS_FILE := "model"
endif
endif

TARGETS_FILE_PATH := $(TOP_PATH)/targets/$(TARGETS_FILE)
BUILD_PATH :=$(TARGETS_FILE_PATH)/build

all:product
product:init compile
	cp $(BUILD_PATH)/src/$(TARGETS_FILE) $(TOP_PATH)
	@echo -e "\033[32m \033[05m############ Make $(TARGETS_FILE) done #############\033[m \033[0m"
init:prepare
	@echo $(TARGETS_FILE)	
prepare:
	@if [ ! -e $(TARGETS_FILE_PATH) ];then \
		echo $(TARGETS_FILE_PATH)" file error!" && false; \
	else \
		echo "TARGETS_FILE=$(TARGETS_FILE)" > $(TOP_PATH)/tsfile.mk ;\
	fi
	@echo $(TARGETS_FILE_PATH)

	@if [ ! -d $(TARGETS_FILE_PATH)/build ];then \
		mkdir $(TARGETS_FILE_PATH)/build; \
	fi

compile:
	cmake $(TARGETS_FILE_PATH) -B $(BUILD_PATH) -DTARGETS=$(TARGETS_FILE)
	make -C $(BUILD_PATH)
run:
	@/$(BUILD_PATH)/$(TARGETS_FILE)

new:
ifdef tsfile
	@if [ ! -d $(TOP_PATH)/targets/$(tsfile) ];then \
		mkdir -p $(TOP_PATH)/targets/$(tsfile); \
		cp $(TOP_PATH)/targets/model/main.cpp $(TOP_PATH)/targets/$(tsfile)/$(tsfile).cpp -rf; \
		cp $(TOP_PATH)/targets/model/CMakeLists.txt $(TOP_PATH)/targets/$(tsfile)/CMakeLists.txt -rf; \
	else \
		echo "targets exist !"; \
	fi
else
	@make help && false
endif

del:
ifdef tsfile
	@rm -rf $(TOP_PATH)/targets/$(tsfile)
else
	@make help && false
endif

cclean:clean
	rm -rf $(TOP_PATH)/tsfile.mk
clean:
	rm -rf $(BUILD_PATH)
	rm -rf $(TOP_PATH)/$(TARGETS_FILE)
	rm -rf $(TOP_PATH)/targets/$(tsfile)/lib
	@echo -e "\033[32m \033[05m############ clean $(TARGETS_FILE) done #############\033[m \033[0m"

help:
	@echo "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
	@echo "		make new tsfile=<xx>"
	@echo "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
